var MongoClient = require('mongodb').MongoClient,
	mongo = require('mongodb'),
	format = require('util').format;
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : 27017;
console.log(">> Connecting to " + host + ":" + port);
function User(user){
	this.name = user.name;
	this.password = user.password;
	this.email = user.email;
}
module.exports = User;
User.prototype.save = function(callback){
	var user = {
		name : this.name,
		password : this.password,
		email : this.email
	};

	MongoClient.connect(format("mongodb://%s:%s/blog", host, port), function(err, db) {
		if(err){
			return callback(err);
		}
		db.collection('users',function(err,collection){
			if(err){
				db.close();
				return callback(err);
			}
			collection.insert(user,{
				safe:true
			},function(err,user){
				if(err){
					return callback(err);
				}
				callback(null,user[0]);
			});
		});
	});
};
User.get = function(name, callback){
	MongoClient.connect(format("mongodb://%s:%s/blog", host, port), function(err, db) {
		if(err){
			callback(err);
		}
		db.collection('users',function(err,collection){
			if(err){
				db.close();
				return callback(err);
			}
			collection.findOne({
				name:name
			},function(err, user){
				db.close();
				if(err){
					return callback(err);
				}
				callback(null,user);
			});
		});
	});
};